//
//  MK_BarrageManagerPacketModel.m
//  miku直播
//
//  Created by 杨尚达 on 2017/7/21.
//  Copyright © 2017年 杨尚达. All rights reserved.
//

#import "MK_BarrageManagerPacketModel.h"

@implementation MK_BarrageManagerPacketModel


- (instancetype)init
{
    self = [super init];
    if (self) {
        self.encryStr = 0;
        self.reserveStr = 0;
    }
    return self;
}

-(unsigned int)dataLength{
    NSData* content = [self.contentStr dataUsingEncoding:NSUTF8StringEncoding];
    return (unsigned int)(8 + content.length+1);
}


///得到数据包
-(NSData*)getRawData{
    NSMutableData* rawData = [NSMutableData new];
    unsigned int length = (self.dataLength);
    unsigned char endStr = '\0';
    [rawData appendBytes:&length length:4];
    [rawData appendBytes:&length length:4];
    [rawData appendBytes:&_type length:2];
    [rawData appendBytes:&_encryStr length:1];
    [rawData appendBytes:&_reserveStr length:1];
    [rawData appendData:[self.contentStr dataUsingEncoding:NSUTF8StringEncoding]];
    [rawData appendBytes:&endStr length:1];
    return rawData;
}

///将二进制包转模型
+(instancetype)MK_BarrageManagerPacketModelWithRawData:(NSData*)data{
    MK_BarrageManagerPacketModel* model = [MK_BarrageManagerPacketModel new];
    unsigned int length;
    MK_BarrageManagerPacketModelType type;
    unsigned char encryStr;
    unsigned char reserveStr;
    [data getBytes:&length range:NSMakeRange(0, 4)];
    [data getBytes:&type range:NSMakeRange(4, 2)];
    [data getBytes:&encryStr range:NSMakeRange(6, 1)];
    [data getBytes:&reserveStr range:NSMakeRange(7, 1)];
    model.type = type;
    model.encryStr = encryStr;
    model.reserveStr = reserveStr;
    NSData* contentData = [data subdataWithRange:NSMakeRange(8, length-8-1)];
    model.contentStr = [[NSString alloc]initWithData:contentData encoding:NSUTF8StringEncoding];
    return model;
}

@end
